package com.today.usercenter.ui.activities;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;

import android.text.InputType;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.today.lib.common.Global;
import com.today.lib.common.ui.base.RxBaseActivity;
import com.today.lib.common.utils.ToastUtils;
import com.today.usercenter.R;
import com.today.usercenter.R2;
import com.today.usercenter.bus.events.LoginEvent;
import com.today.usercenter.network.entity.request.LoginRequestEntity;
import com.today.usercenter.network.entity.request.QqLoginRequestEntity;
import com.today.usercenter.network.entity.request.WxLoginRequestEntity;
import com.today.usercenter.utils.InputUtils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.reactivestreams.Subscription;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import butterknife.BindView;


/**
 * Created by cgm on 18-6-19.
 */

public class LoginActivity extends RxBaseActivity implements View.OnClickListener {
    private static final String TAG = LoginActivity.class.getSimpleName();
    private Activity mActivity;

//    @BindView(R2.id.sina_platform_btn)
//    LinearLayout mWeiboLayout;
    @BindView(R2.id.qq_platform_btn)
    LinearLayout mQQLayout;
    @BindView(R2.id.weixin_platform_btn)
    LinearLayout mWeixinLayout;
//    @BindView(R2.id.mobile)
//    EditText mMobile;
//    @BindView(R2.id.password)
//    EditText mPassword;
//    @BindView(R2.id.login)
//    TextView mLogin;
//    @BindView(R2.id.register)
//    TextView mRegister;
//    @BindView(R2.id.reset_pwd)
//    TextView mRestPwd;
    @BindView(R2.id.rules)
    TextView mRules;
    @BindView(R2.id.toolbar)
    QMUITopBar mToolbar;

    private UMShareAPI mUMShareAPI;

    private DisplayMetrics mDisplayMetrics;

    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };


    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        mActivity = this;
        mDisplayMetrics = new DisplayMetrics();
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);

        getPermission();
        mUMShareAPI = UMShareAPI.get(mActivity);

        initToolbar();

        EventBus.getDefault().register(this);
    }

    private void initToolbar() {
        mToolbar.setBackgroundColor(ContextCompat.getColor(this, com.today.lib.common.R.color.colorPrimary));
        mToolbar.addLeftBackImageButton().setOnClickListener(v -> onBackPressed());
        mToolbar.setTitle(R.string.login);
    }

    /**
     * 华为6.0手机没有权限获取图片，需要申请权限
     *
     * @author jqt
     * create at 2017/4/10 19:40
     */
    private void getPermission() {
        // 是否添加权限
        int permission = ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        //如果没有权限,申请权限
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(mActivity, PERMISSIONS_STORAGE, 11);
        } else {
            initView();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 请求权限成功，无论点击禁止还是允许都是请求权限成功
        if (requestCode == 11) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initView();
            } else {
                ToastUtils.showToast(R.string.please_open_permissions);
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void gotLoginMessage(LoginEvent loginEvent) {
        if (loginEvent.status == LoginEvent.STATUS_LOGIN)
            finish();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
//        mWeiboLayout.setOnClickListener(this);
        mQQLayout.setOnClickListener(this);
        mWeixinLayout.setOnClickListener(this);
//        mLogin.setOnClickListener(this);
//        mRegister.setOnClickListener(this);
//        mRestPwd.setOnClickListener(this);
        mRules.setOnClickListener(this);

        // 设置密码是否显示
//        mPassword.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Drawable drawable = mPassword.getCompoundDrawables()[2];
//                if (drawable == null) {
//                    return;
//                }
//                if (mPassword.getInputType() == InputType.TYPE_CLASS_TEXT) {
//                    drawable = getResources().getDrawable(R.drawable.pwd_gone);
//                    drawable.setBounds(0, 0, (int) (24 * density), (int) (13 * density));
//                    mPassword.setCompoundDrawables(null, null, drawable, null);
//                    mPassword.setInputType(InputType.TYPE_CLASS_TEXT
//                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
//                    mPassword.setSelection(mPassword.getText().length());
//                } else if (mPassword.getInputType() == (InputType.TYPE_CLASS_TEXT
//                        | InputType.TYPE_TEXT_VARIATION_PASSWORD)) {
//                    drawable = getResources().getDrawable(R.drawable.pwd_visible);
//                    drawable.setBounds(0, 0, (int) (24 * density), (int) (13 * density));
//                    mPassword.setCompoundDrawables(null, null, drawable, null);
//                    mPassword.setInputType(InputType.TYPE_CLASS_TEXT);
//                    mPassword.setSelection(mPassword.getText().length());
//                }
//            }
//        });
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.qq_platform_btn) {
            if (mUMShareAPI.isInstall(mActivity, SHARE_MEDIA.QQ)) {
                getUserInfo(SHARE_MEDIA.QQ);
            } else {
                ToastUtils.showToast(getString(R.string.qq_not_installed));
            }

        } else if (i == R.id.weixin_platform_btn) {
            if (mUMShareAPI.isInstall(mActivity, SHARE_MEDIA.WEIXIN)) {
                getUserInfo(SHARE_MEDIA.WEIXIN);
            } else {
                ToastUtils.showToast(getString(R.string.wx_not_installed));
            }

//        } else if (i == R.id.login) {
//            if (!InputUtils.isLegalCellphone(mMobile.getText().toString())) {
//                ToastUtils.showToast(getString(R.string.mobile_error));
//            } else if (!InputUtils.isLegalPwd(mPassword.getText().toString())) {
//                ToastUtils.showToast(getString(R.string.please_input_legal_mobile));
//            } else {
//                LoginRequestEntity rqst = new LoginRequestEntity(mMobile.getText().toString(),
//                        InputUtils.encodeUserPwd(mPassword.getText().toString()));
//
//                Global.loginHelper.login(rqst);
//            }
//
//        } else if (i == R.id.register) {
//            Intent intent = new Intent(mActivity, RegisterActivity.class);
//            intent.putExtra("type", RegisterActivity.TYPE_REGISTER);
//            startActivity(intent);
//
//        } else if (i == R.id.reset_pwd) {
//            Intent intent = new Intent(mActivity, RegisterActivity.class);
//            intent.putExtra("type", RegisterActivity.TYPE_RESET_PWD);
//            startActivity(intent);

        } else if (i == R.id.rules) {
            new QMUIDialog.MessageDialogBuilder(mActivity)
                    .setMessage(getString(R.string.declare))
                    .setTitle("隐私政策")
                    .addAction("不同意", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                            finish();
                        }
                    })
                    .addAction("同意", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    })
                    .show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mUMShareAPI.onActivityResult(requestCode, resultCode, data);
    }

    private void getUserInfo(final SHARE_MEDIA platform) {
        mUMShareAPI.getPlatformInfo(mActivity, platform, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                Log.d(TAG, "onComplete1");
                Log.d(TAG, "map1:" + map);
                if (map != null) {
                    if (share_media == SHARE_MEDIA.WEIXIN) {
                        WxLoginRequestEntity rqst = new WxLoginRequestEntity(map);
                        Global.loginHelper.login(rqst);
                    } else if (share_media == SHARE_MEDIA.QQ) {
                        QqLoginRequestEntity rqst = new QqLoginRequestEntity(map);
                        Global.loginHelper.login(rqst);
                    }
                } else {
                    ToastUtils.showToast(getString(R.string.auth_fail));
                }
            }


            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                Log.d(TAG, "onError1");
                Log.d(TAG, "share_media:" + share_media);
                throwable.printStackTrace();
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                Log.d(TAG, "onCancel1");

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUMShareAPI.release();

        EventBus.getDefault().unregister(this);
    }

    /**
     * 把字符类型转化为时间戳
     *
     * @param time
     * @return
     */
    public long strToTimeStamp(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        try {
            Date date = sdf.parse(time);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0L;
    }
}
